package person.drf.shop.product.jucTest;

/**
 * 题目：现在两个线程，可以操作初始值为0的一个变量
 *      实现一个线程对该变量加，一个线程对该变量减1，
 *      实现交替，来10轮，变量初始值为零。
 *
 */
class AirConditioner{    //资源类
    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        //1.判断
        while(number!=0){
           this.wait();
        }
        //2.干活
        number++;
        System.out.println(Thread.currentThread().getName()+"--"+number);
        //3.通知
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        //1.判断
        while(number==0){
            this.wait();
        }
        //2.干活
        number--;
        System.out.println(Thread.currentThread().getName()+"--"+number);
        //3.通知
        this.notifyAll();
    }
}

public class ProConDemo {
    public static void main(String[] args) {
        AirConditioner airConditioner = new AirConditioner();

         new Thread(()->{
             for (int i = 0; i < 10; i++) {
                 try {
                     airConditioner.increment();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         },"A").start();  //  +

         new Thread(()->{
             for (int i = 0; i < 10; i++) {
                 try {
                     airConditioner.increment();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
         },"B").start();  //  +

         new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();  //  -

         new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    airConditioner.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();  //  -
    }
}
